﻿using DTcms.Core.Common.Helper;
using DTcms.Core.IServices;
using DTcms.Core.Model.Models;
using Microsoft.AspNetCore.Mvc;

namespace DTcms.Core.API.Controllers
{
    /// <summary>
    /// 用户下载数据
    /// </summary>
    [Area("api")]
    [Route("api/[controller]")]
    [ApiController]
    public class DownloadController : ControllerBase
    {
        private readonly IWebHostEnvironment _hostEnvironment;
        private readonly IArticleAttachService _attachService;
        private readonly IArticleService _articleService;
        private readonly IUserService _userService;
        private readonly IHttpClientFactory _clientFactory;

        /// <summary>
        /// 依赖注入
        /// </summary>
        public DownloadController(IArticleService articlesService, IUserService userService,
            IArticleAttachService attachService, IHttpClientFactory clientFactory, IWebHostEnvironment hostEnvironment)
        {
            _articleService = articlesService;
            _userService = userService;
            _clientFactory = clientFactory;
            _attachService = attachService;
            _hostEnvironment = hostEnvironment;
        }

        #region 前台调用接口============================
        /// <summary>
        /// 下载文件
        /// </summary>
        [HttpGet("/api/client/download/{id}")]
        public async Task<IActionResult> Download([FromRoute] long id)
        {
            //获得下载ID
            if (id == 0)
            {
                return BadRequest(ResponseMessage.Error("出错了，文件参数传值不正确！"));
            }
            //获取登录用户
            var userModel = await _userService.GetUserAsync();
            if (userModel == null)
            {
                return Unauthorized(ResponseMessage.Error("下载失败，请登录后下载"));
            }

            var attachModel = await _attachService.QueryAsync<ArticleAttach>(t => t.Id == id);
            if (attachModel == null || attachModel.FilePath == null)
            {
                return BadRequest(ResponseMessage.Error("出错了，文件不存在或已删除！"));
            }
            attachModel.DownCount++;
            //检查文件本地还是远程
            if (attachModel.FilePath.ToLower().StartsWith("http://") || attachModel.FilePath.ToLower().StartsWith("https://"))
            {
                var client = _clientFactory.CreateClient();
                var responseStream = await client.GetStreamAsync(attachModel.FilePath);
                if (responseStream == null)
                {
                    return BadRequest(ResponseMessage.Error("出错了，文件不存在或已删除！"));
                }
                byte[] byteData = FileHelper.ConvertStreamToByteBuffer(responseStream);
                //更新下载数量
                await _attachService.UpdateDownCount(id, userModel);
                return File(byteData, "application/octet-stream", attachModel.FileName);
            }
            else
            {
                string webRootPath = _hostEnvironment.WebRootPath;
                //获取物理路径
                string fullFileName = (webRootPath + attachModel.FilePath).Replace("\\", @"/");
                //检测文件是否存在
                if (!System.IO.File.Exists(fullFileName))
                {
                    return BadRequest(ResponseMessage.Error("出错了，文件不存在或已删除！"));
                }
                //更新下载数量
                await _attachService.UpdateDownCount(id, userModel);
                return File(attachModel.FilePath, "application/octet-stream", attachModel.FileName);
            }
        }
        #endregion
    }
}
